package com.ia.aistream.manager.framework.misc;

import com.ia.aistream.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import sun.misc.Signal;
import sun.misc.SignalHandler;

/**
 * 退出系统时处理
 * @author chenjunsheng
 */
@Slf4j
@Component
public class SignalHandlerConfiger implements InitializingBean, SignalHandler {

    @Override
    public void afterPropertiesSet() throws Exception {
//        Signal.handle(new Signal("HUP"), this);
        Signal.handle(new Signal("INT"), this);
//        Signal.handle(new Signal("ALRM"), this);
        Signal.handle(new Signal("TERM"), this);
    }

    @Override
    public void handle(Signal signal) {
        log.info("系统进程即将关闭，捕抓到信号量为：{}，{}", signal.getNumber(), signal.getName());
        String[] beanNames = SpringUtils.getBeanNamesForType(SystemExitListner.class);
        for (String beanName : beanNames) {
            try {
                SystemExitListner listner = SpringUtils.getBean(beanName, SystemExitListner.class);
                listner.onBeforeExit();
            } catch (Exception e) {
                log.error("系统进程即将关闭事件处理异常:", e);
            }

        }
        // 退出程序
        System.exit(0);
    }
}
